import { useState, useRef } from 'react';
import { View, Input, Text } from '@tarojs/components';
import { AtButton, AtCheckbox } from 'taro-ui';
import IconFont from '@/assets/Iconfont';
import cssModule from './index.module.scss';
import { register, sendSms, syncLocation, wxLogin } from '@/business/services/user/login/login';
import { useRouter } from '@tarojs/taro';
import Taro from '@tarojs/taro';
import { initUser } from '@/business/services/im';
import { isPhoneNumber } from '@/utils/validate';
import { getAuthCode, setAuthCode } from '@/base/auth/authCode';
import { cityTreeListStore } from '@/business/store/city/city';

/**
 * @description 手机验证码注册
 * @author Shawn
 */

export default function PhoneRegister() {
    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [countdown, setCountdown] = useState(0);
    const timerRef = useRef<NodeJS.Timeout | null>(null);
    const [agreementChecked, setAgreementChecked] = useState<string[]>([]);

    const router = useRouter()

    // 设置当前城市
    const setLocation = async () => {
        const res = await Taro.getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
        });
        const { latitude, longitude } = res;

        if (latitude && longitude) {
            await syncLocation({ latitude, longitude })
        }
    }

    // 发送验证码
    const handleSendCode = () => {
        if (!isPhoneNumber(phone)) {
            Taro.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            })
            return
        }

        if (countdown > 0) return;
        // 这里可以添加手机号校验逻辑
        setCountdown(60);
        timerRef.current = setInterval(() => {
            setCountdown((prev) => {
                if (prev <= 1) {
                    clearInterval(timerRef.current!);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);
        // TODO: 这里可以添加发送验证码的接口调用
        sendSms({ scene: 'login', phone: phone });
    };

    // 获取城市数据
    const getCityTreeList = async () => {
        await cityTreeListStore.getState().getCityTreeList();
    }

    const onRegister = async () => {
        console.log(agreementChecked, 'agreementChecked')
        if (!agreementChecked.length) {
            Taro.showToast({
                title: '请同意用户协议和隐私政策',
                icon: 'none'
            })
            return
        }
        try {
            const params = {
                cellphone: phone,
                smsCode: code,
                wxOpenid: router.params.openid,
                inviteCellphone: '',
            }
            const inviteCellphone = Taro.getStorageSync('inviteCellphone')
            if (inviteCellphone) {
                params.inviteCellphone = inviteCellphone
            }
            const res = await register(params)

            Taro.setStorageSync('openToken', res.data);
            await setAuthCode();
            const authCode = await getAuthCode();
            const authRes = await wxLogin({
                code: authCode,
            });
            Taro.setStorageSync('userId', authRes.data.userId);
            Taro.setStorageSync('openid', authRes.data.openid);
            const userSig = Taro.getStorageSync('imUserSig');
            await setLocation()
            if (!userSig) {
                const imRes = await initUser({})
                Taro.setStorageSync('imUserSig', imRes.data.imUserId);
            }
            Taro.setStorageSync('isLogin', true);
            getCityTreeList()
            // 注册成功跳转到首页
            Taro.redirectTo({
                url: '/subPackages/person/index'
            })
        } catch (error) {
            console.log(error)
        }
    }

    const onAgreement = () => {
        Taro.navigateTo({
            url: '/subPackages/agreement/index'
        })
    }

    const onprivacyPolicy = () => {
        Taro.navigateTo({
            url: '/subPackages/privacyPolicy/index'
        })
    }

    const [phoneCursor, setPhoneCursor] = useState(0)
    const [codeCursor, setCodeCursor] = useState(0)

    return (
        <View className={cssModule.container}>
            <View className={cssModule.phoneRow}>
                <IconFont name='shouji' size={36} />
                <Input
                    className={cssModule.input}
                    placeholder='手机号'
                    type='number'
                    value={phone}
                    cursor={phoneCursor}
                    onInput={(e) => {
                        setPhone(e.detail.value)
                        setPhoneCursor(e.detail.cursor)
                    }}
                    maxlength={11}
                />
            </View>
            <View className={cssModule.codeRow}>
                <IconFont name='mima' size={36} />
                <Input
                    className={cssModule.input}
                    placeholder='请输入验证码'
                    type='number'
                    value={code}
                    cursor={codeCursor}
                    onInput={(e) => {
                        setCode(e.detail.value)
                        setCodeCursor(e.detail.cursor)
                    }}
                    maxlength={6}
                />
                <View className={cssModule.sendBtn} onClick={handleSendCode}>
                    {countdown > 0 ? `${countdown}s后重试` : '发送验证码'}
                </View>
            </View>
            <View className={cssModule.agreement}>
                <View className={cssModule.checkboxContainer}>
                    <AtCheckbox
                        options={[{ label: '', value: 'agree' }]}
                        selectedList={agreementChecked}
                        onChange={(value) => setAgreementChecked(value)}
                    />
                    <Text>已经阅读并同意</Text>
                    <Text className='text-[#6190e8]' onClick={onAgreement}>《用户协议》</Text>
                    <Text>和</Text>
                    <Text className='text-[#6190e8]' onClick={onprivacyPolicy}>《隐私政策》</Text>
                </View>
            </View>
            <View className={cssModule.registerBtn}>
                <AtButton type='primary' onClick={onRegister}>注册</AtButton>
            </View>
        </View>
    );
}
